const app = getApp()
import {
  getMchInfo,
  openCity
} from '../../api/amap'

const util = require('../../utils/util.js')
import { pinyin } from '../../utils/pinyin-pro.min'
Page({
  data: {
    openCityList: [],
    cityName: app.globalData.cityName,
    nowCityName: app.globalData.cityName,
    cityIndexList: [],
    active: 0,
    topHeight: 0,
    windowHeight: app.globalData.windowHeight,
    safeAreaBottom: 22,
    statusBarHeight: app.globalData.statusBarHeight,
    windowWidth: 0,
    scrollTop: 0,
    topTitleList: [],
    popupTime: null,
    queryFocus: false,
    queryText: '',
    queryList: [],
    inputTimer: null
  },
  onShow: function () {
    wx.showLoading({
      title: '加载中',
    })
    wx.hideNavigationBarLoading()
    this.getPageSize();
    this.openCity()
    this.setData({
      cityName: app.globalData.cityName,
    })
    this.getPageSize()
    this.toSelectArea()
  },
  scanClick() {
    var _this = this
    wx.scanCode({
      success(res) {
        if (!util.isNull(res.result)) {
          //扫码进入
          let s = decodeURIComponent(res.result);
          app.globalData.q = s
          if (s.indexOf('/q/88') == -1 && s.indexOf('/q/89') == -1) {
            if (s.indexOf('?productId') != -1) {
              let e = s.indexOf('?productId');
              let w = s.indexOf('/q/');
              let x = s.substring(w + 3, e);
              let d = s.substring(e + 11);
              app.globalData.xuid = x;
              _this.getInfoClick()
            } else if (s.indexOf('?groupBuyId') != -1) {
              let e = w = s.indexOf('?groupBuyId');
              let w = s.indexOf('/q/');
              let x = s.substring(w + 3, e);
              let d = s.substring(e + 12);
              app.globalData.xuid = x;
              _this.getInfoClick()
            } else {
              let w = s.indexOf('/q/');
              let x = s.substring(w + 3);
              app.globalData.xuid = x;
              _this.getInfoClick()
            }
          }
        }
      }
    })
  },
  getInfoClick(e, city = null) {
    const { id } = !util.isNull(e) ? e.currentTarget.dataset.item : city
    console.log(id)
    wx.setStorageSync('areaId', id);
    var _this = this
    getMchInfo({ xuid: app.globalData.xuid, areaId: id }).then(res => {
      if (res.data != null && res.data.sysMch != null) {
      console.log(res,'switch-res');
      app.globalData.mchId = res.data.sysMch.id
        app.globalData.mchName = res.data.sysMch.name
        app.globalData.location = true;
        app.globalData.cityName = res.data.cityName
      }
      if (_this.userInfoReadyCallback) {
        app.globalData.loaded = true;
        _this.userInfoReadyCallback(res)
      }
      console.log(app.globalData,'switch');
      wx.navigateBack({
        delta: 1,
        complete: (res) => { },
      })
    }).catch(error => {
      console.log(error)
    })
  },
  storeClick() {
    wx.navigateTo({
      url: '/pages/index/storeList'
    })
  },
  openCity(callback) {
    openCity().then(res => {
      this.data.openCityList = res.data.areaList
      let cityIndexList = []
      let indexList = []
      //通过返回数据获取城市索引
      this.data.openCityList.map((el) => {
        let pyList = []
        pyList = pinyin(el.name, { pattern: 'first', toneType: 'none', type: 'array' })
        indexList.push(pyList[0])
      })
      //城市索引去重并排序
      indexList = Array.from(new Set(indexList)).sort()
      indexList.map((py, pyIndex) => {
        //根据索引初始化树形结构
        cityIndexList[pyIndex] = {
          index: py.toUpperCase(),
          childrens: []
        }
        //根据索引长度依次遍历城市数据
        this.data.openCityList.map((el) => {
          let tmp = pinyin(el.name, { pattern: 'first', toneType: 'none', type: 'array' })
          //判断城市索引与城市数据是否相同，相同则放对对应索引的childrens中
          if (py == tmp[0]) cityIndexList[pyIndex].childrens.push(el);
        })
      })
      this.data.cityIndexList = cityIndexList
      this.setData({
        openCityList: this.data.openCityList,
        cityIndexList: this.data.cityIndexList,
      })
      wx.hideLoading()
      if (callback) {
        callback()
      }
    })
  },
  getNodesInfo() {//滚动的距离
    const that = this
    const selectorQuery = wx.createSelectorQuery();
    // 获取节点的位置信息
    selectorQuery.select('.city_header').boundingClientRect(function (rect) {
      that.data.topHeight = rect.bottom * that.data.rpxR
      that.setData({
        topHeight: that.data.topHeight + 10
      })
    }).exec()
    selectorQuery.select('.query_box').boundingClientRect(function (rect) {
      that.data.queryHeight = rect.height * that.data.rpxR
      that.setData({
        queryHeight: that.data.queryHeight
      })
    }).exec()
    selectorQuery.selectAll('.rigtht_content_title').boundingClientRect(function (rects) {
      // 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
      that.data.topTitleList = []
      var timer = null
      if (!rects.length) {
        timer = setTimeout(() => {
          that.getNodesInfo();
          clearTimeout(timer)
        }, 200);
        return;
      }
      // 生成之后开始添加进去数组
      rects.forEach((el) => {
        let top = el.top - rects[0].top// 这里减去rects[0].top，是因为第一项顶部不是贴到导航栏=>每一个商品距离顶部的高度，如果此页面顶部没有其他的view那就不用减去rects[0].top，自己视情况而定。
        that.data.topTitleList.push({ top: top, id: el.id, index: el.dataset.index });
      })
    }).exec()
    selectorQuery.selectAll('.menu-item').boundingClientRect(function (rects) {
      // 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
      that.data.topClassifyList = []
      var timer = null
      if (!rects.length) {
        timer = setTimeout(() => {
          that.getNodesInfo();
          clearTimeout(timer)
        }, 200);
        return;
      }
      // 生成之后开始添加进去数组
      rects.forEach(el => that.data.topClassifyList.push({ height: el.height, top: el.top, bottom: el.bottom, index: el.dataset.index, eindex: el.dataset.eindex }))
    }).exec()
  },
  getPageSize() {
    const that = this
    const sysinfo = wx.getSystemInfoSync(),
      rpxR = 750 / sysinfo.windowWidth;
    that.data.windowWidth = sysinfo.windowWidth * rpxR;
    that.data.windowHeight = sysinfo.windowHeight * rpxR;
    that.data.screenHeight = sysinfo.screenHeight * rpxR;
    that.data.safeAreaBottom = (sysinfo.screenHeight - sysinfo.safeArea.bottom) * rpxR;
    that.data.rpxR = rpxR;

    this.setData({
      safeAreaBottom: that.data.safeAreaBottom,
      windowWidth: that.data.windowWidth,
      windowHeight: that.data.windowHeight,
      screenHeight: that.data.screenHeight,
      rpxR: rpxR,
    })
    this.getNodesInfo()
  },
  selectMenu(e) {
    const { index, eindex } = e.currentTarget.dataset
    this.data.showPopup = true
    this.data.active = index
    this.data.scrollTop = this.data.topTitleList[index].top
    this.setData({
      active: this.data.active,
      popupText: eindex,
      scrollTop: this.data.scrollTop,
      showPopup: this.data.showPopup,
    })
    clearTimeout(this.data.popupTime)
    this.data.popupTime = setTimeout(() => {
      this.data.showPopup = false
      this.setData({
        showPopup: this.data.showPopup,
      })
    }, 600)
  },
  watch: function (path, callback) {
    let value = this.data[path];
    const that = this;
    Object.defineProperty(this.data, path, {
      configurable: true,
      enumerable: true,
      get: function () {
        return value;
      },
      set: function (newVal) {
        if (newVal !== value) {
          const oldVal = value;
          value = newVal;
          callback(newVal, oldVal);
        }
      }
    });
  },
  rigthTouchmove(e) {
    console.log(e)
    const { pageY } = e.touches[0]
    // if (e.type == "touchstart") {
    //   wx.pageScrollTo({
    //     disableScroll: true
    //   })
    // }

    this.data.topClassifyList.map((el, index) => {
      if (pageY >= el.top - 3 && el.bottom - 3 >= pageY) {
        this.setData({
          popupText: el.eindex,
          showPopup: true,
          scrollTop: this.data.topTitleList[index].top
        })
        clearTimeout(this.data.popupTime)
        this.data.popupTime = setTimeout(() => {
          this.setData({
            showPopup: false,
          })
        }, 600)
      }
    })
  },
  toSelectArea(e) {
    if (!util.isNull(e)) {
      wx.showLoading({
        title: '定位中',
      })
    }
    wx.getLocation({
      type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      isHighAccuracy: true,
      success: res => {
        app.globalData.lat = res.latitude
        app.globalData.lng = res.longitude
        app.getGeoCode(res.latitude, res.longitude).then(res => {
          this.data.nowCityName = res.data.areaName.substring(res.data.areaName.indexOf("省") + 1, res.data.areaName.indexOf("市") + 1)
          this.setData({
            nowCityName: this.data.nowCityName,
          })
          wx.hideLoading()
        })
      },
      fail: err => {
        console.log(err)
        wx.hideLoading()
      }
    })
  },
  selectCity() {
    this.data.openCityList.map(el => {
      if (el.name == this.data.nowCityName) {
        this.getInfoClick(null, el)
      }
    })
  },
  cityFocusChange() {
    this.setData({
      queryFocus: true
    })
  },
  cityInputChange(e) {
    const { value } = e.detail
    const that = this
    this.setData({
      queryText: value
    })
    clearTimeout(this.data.inputTimer)
    this.data.inputTimer = setTimeout(() => {
      that.queryCity(value)
    }, 800)
  },
  cityCleanChange() {
    this.setData({
      queryFocus: true,
      queryList: [],
      queryText: '',
    })
  },
  cityCancelChange() {
    this.setData({
      queryFocus: false,
      queryList: [],
      queryText: '',
    })
  },
  queryCity(value) {
    const chineseReg = /^[\u4E00-\u9FA5]+$/;
    const isChinese = chineseReg.test(value)
    let queryList = []
    if (value.length > 0) {
      this.data.openCityList.map((el) => {
        let py = pinyin(el.name, { pattern: 'first', toneType: 'none', type: 'array' })
        let pyAll = pinyin(el.name, { pattern: 'pinyin', toneType: 'none', type: 'array' })
        if (!isChinese) {
          if (value.length == 1 && value.toUpperCase() == py[0].toUpperCase()) {
            queryList.push(el)
          } else {
            py = py.join('').toUpperCase();
            pyAll = pyAll.join('').toUpperCase();
            if (py.indexOf(value.toUpperCase()) > -1 || pyAll.indexOf(value.toUpperCase()) > -1) {
              queryList.push(el)
            }
          }
        } else {
          if (el.name.indexOf(value) > -1) {
            queryList.push(el)
          }
        }
      })
    }
    this.setData({
      queryList: queryList
    })
  }
})